//
// Created by Administrator on 2023-12-07.
//

#include "MyTcpServer.h"
#include"mainwindow.h"

MainWindow*dddd;
MyTcpServer::MyTcpServer(QObject* parent) {
    server = new QTcpServer();
    _mainWindow=parent;
    qDebug()<<"111111"<<_mainWindow->objectName();
    // clients=new std::map<QString, QTcpSocket *>();
     dddd= static_cast<MainWindow*>(_mainWindow) ;


}

MyTcpServer::~MyTcpServer() {
    server->close();
    server->destroyed();
    server->deleteLater();
}

void MyTcpServer::connectServer() {
    if (!server->listen(QHostAddress::Any, port)) {
        qCritical() << "启动服务器失败";
    }
    qDebug() << "server start listening on port " << port;
    QObject::connect(server, &QTcpServer::newConnection, [&]() {
        qDebug() << "按钮点击启动";
        QTcpSocket *socket = server->nextPendingConnection();
        qDebug() << "New connection from:" << socket->peerAddress().toString();
        QString ip = socket->peerAddress().toString();
        quint16 port = socket->peerPort();
        QString key= ip + ":" + QString::number(port);
        qDebug()<<"key"<<key.toStdString() ;



        clients.insert(key,socket);
         dddd->print_test(std::to_string(clients.size()));
        massSend(std::to_string(clients.size()));
        QObject::connect(socket, &QTcpSocket::readyRead, [socket]() {
            QByteArray data = socket->readAll();
            qDebug() << "Data received:" << data;
            dddd->rcvText->append(data);
            // Echo the data back to the client
            socket->write(data);
        });

        QObject::connect(socket, &QTcpSocket::disconnected, [&]() {
            auto  endSocket=socket;


           //  qDebug() << "Client disconnected:" << endSocket->peerAddress().toString();
           //  QString ip = endSocket->peerAddress().toString();
           //  quint16 port = endSocket->peerPort();
           // QString removeKey= ip + ":" + QString::number(port);
           // qDebug()<<removeKey;
           // massSend(to_string(clients.size()));
           // clients.remove(removeKey);
            //socket->deleteLater();
        });
    });
}

void MyTcpServer::stopServer() {
    server->close();
    server->destroyed();
    server->deleteLater();

}
void MyTcpServer::massSend(std::string message){
    for(auto const& socket:clients){
        socket->write(message.c_str());
    }
}
